<template>
  <el-drawer
      v-model="showFlag"
      append-to-body
      :before-close="cancel">
    <div style="margin: 20px">
      <el-form :model="refForm" :rules="rules" ref="formView" label-position="top" size="default">

        <el-row>
          <el-col :span="24">
            <el-button-group class="flex-warp-item">
              <el-button :type="refForm.menuType==item.dictValue?'primary':'default'"
                         @click="menuTypeSelect(item.dictValue)" v-for="item in menuTypeOptions" key="index">
                {{ item.dictLabel }}
              </el-button>
            </el-button-group>
          </el-col>
          <el-col :span="24">
            <el-form-item label="上级菜单" prop="parentId" class="mt10">
              <el-tree-select style="width: 100%" node-key="menuId" v-model="refForm.parentId"
                              :props="{label: 'title',children: 'children'}"
                              :data="menuList" check-strictly/>
            </el-form-item>
          </el-col>
          <el-col :span="24" class="mt10">
            <el-form-item :label="nameLabel" prop="title">
              <el-input v-model="refForm.title"/>
            </el-form-item>
          </el-col>
          <el-col :span="24" class="mt10">
            <el-form-item label="排序" prop="orderNum">
              <el-input-number :min="0" v-model="refForm.orderNum"/>
            </el-form-item>
          </el-col>
          <el-col :span="24" class="mt10">
            <el-form-item label="权限标识" prop="perms">
              <el-input v-model="refForm.perms"/>
            </el-form-item>
          </el-col>
          <el-col :span="24" class="mt10">
            <el-form-item label="图标" prop="icon" v-if="refForm.menuType==='C'">
              <IconSelector v-if="showFlag" @get="onGetIcon" @clear="onClearIcon" v-model="refForm.icon" type="all"/>
            </el-form-item>
          </el-col>
          <el-col :span="24" class="mt10">
            <el-form-item label="路由地址" prop="path" v-if="refForm.menuType==='C'">
              <el-input v-model="refForm.path"/>
            </el-form-item>
          </el-col>
          <el-col :span="24" class="mt10">
            <el-form-item label="组件名称" prop="menuName" v-if="refForm.menuType==='C'">
              <el-input v-model="refForm.menuName"/>
            </el-form-item>
          </el-col>
          <el-col :span="24" class="mt10">
            <el-form-item label="组件路径" prop="component" v-if="refForm.menuType==='C'">
              <el-input v-model="refForm.component"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="mt10">
            <el-form-item label="是否外链" prop="isLink" v-if="refForm.menuType==='C'">
              <el-radio-group v-model="refForm.isLink" @change="linkChange">
                <el-radio v-for="item in commonIsNotOptions" :label="item.dictValue">{{ item.dictLabel }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="12" class="mt10">
            <el-form-item label="是否内嵌" prop="isIframe" v-if="refForm.menuType==='C'">
              <el-radio-group v-model="refForm.isIframe" @change="iframeChange">
                <el-radio v-for="item in commonIsNotOptions" :label="item.dictValue">{{ item.dictLabel }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24" class="mt10">
            <el-form-item label="内嵌/外链地址" prop="link" v-if="refForm.menuType==='C'">
              <el-input v-model="refForm.link" :disabled="!(refForm.isLink==='0'|| refForm.isIframe==='0')"/>
            </el-form-item>
          </el-col>

          <el-col :span="12" class="mt10">
            <el-form-item label="是否隐藏" prop="isHide" v-if="refForm.menuType==='C'||refForm.menuType==='M'">
              <el-radio-group v-model="refForm.isHide">
                <el-radio v-for="item in commonIsNotOptions" :label="item.dictValue">{{ item.dictLabel }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="mt10">
            <el-form-item label="是否缓存" prop="isKeepAlive" v-if="refForm.menuType==='C'">
              <el-radio-group v-model="refForm.isKeepAlive">
                <el-radio v-for="item in commonIsNotOptions" :label="item.dictValue">{{ item.dictLabel }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="12" class="mt10">
            <el-form-item label="是否固定" prop="isAffix" v-if="refForm.menuType==='C'||refForm.menuType==='M'">
              <el-radio-group v-model="refForm.isAffix">
                <el-radio v-for="item in commonIsNotOptions" :label="item.dictValue">{{ item.dictLabel }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <template #footer>
      <div style="text-align: center;margin-bottom: 10px">
        <el-button size="default" @click="cancel()">取消</el-button>
        <el-button size="default" type="primary" @click="subimt()" v-auths="['system-menu-add','system-menu-update']">提交</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup>
import IconSelector from '/@/components/iconSelector/index.vue';
import {ElMessage} from "element-plus";
import {addMenu, editMenu} from "/@/api/system/menu";
import {cloneDeep} from 'lodash';

const emits = defineEmits(['ok'])
const props = defineProps({
  menuList: {
    type: Array,
    required: true
  }
})
const formView = ref()


const {proxy} = getCurrentInstance()
const showFlag = ref(false)
const nameLabel = ref('菜单名称')

// 表单验证
const checkPath = (rule, value, callback) => {
  if (refForm.menuType != 'F') {
    if (!value || value === '') {
      callback(new Error('请输入路由地址'))
    } else {
      callback()
    }
  }
}


const checkComponent = (rule, value, callback) => {
  if (refForm.menuType === 'C') {
    if (!value || value === '') {
      callback(new Error('请输入组件路径'))
    } else {
      callback()
    }
  }
}

const checkPerms = (rule, value, callback) => {
  if (refForm.menuType !== 'M') {
    if (!value || value === '') {
      callback(new Error('请输入权限标识'))
    } else {
      callback()
    }
  }
}

const checkIcon = (rule, value, callback) => {
  if (refForm.menuType != 'F') {
    if (!value || value === '') {
      callback(new Error('请选择图标'))
    } else {
      callback()
    }
  }
}



const rules = reactive({
  parentId: [{required: true, message: '请输入选择上级菜单', trigger: 'blur'}],

  title: [{required: true, message: '请输入菜单名称', trigger: 'blur'}],
  path: [{validator: checkPath, trigger: 'blur'}],
  component: [{validator: checkComponent, trigger: 'blur'}],
  perms: [{validator: checkPerms, trigger: 'blur'}],
  icon: [{validator: checkIcon, trigger: 'blur'}]

})
let refForm = reactive({
  menuId: undefined,
  // 菜单类型（C菜单 F按钮）")
  menuType: 'C',
  // 菜单名称")
  title: undefined,
  // 组件名称")
  menuName: undefined,
  // 父菜单ID")
  parentId: undefined,
  // 显示顺序")
  orderNum: 1,
  // 路由地址")
  path: undefined,
  // 组件路径")
  component: undefined,
  // 是否为外链（0是 1否）")
  isLink: '1',
  // 是否内嵌，开启条件，1、isIframe:true 2、isLink：链接地址不为空")
  isIframe: '1',
  // 内嵌或者外联路径https/http开头")
  link: undefined,
  // 菜单状态（0显示 1隐藏）")
  isHide: '1',
  // 是否缓存（0缓存 1不缓存）")
  isKeepAlive: '0',
  // 是否固定（0是 1否）")
  isAffix: '1',
  // 菜单图标")
  icon: undefined,
  // 权限标识")
  perms: undefined,
})

const cancel = () => {
  formView.value.clearValidate()
  formView.value.resetFields()
  nameLabel.value = '菜单名称'

  refForm.menuId= undefined
  refForm.menuType= 'C'
  refForm.title=undefined
  refForm.menuName= undefined
  refForm.parentId= undefined
  refForm.orderNum= 1
  refForm.path= undefined
  refForm.component= undefined
  refForm.isLink= '1'
  refForm.isIframe= '1'
  refForm.link= undefined
  refForm.isHide= '1'
  refForm.isKeepAlive= '0'
  refForm.isAffix= '1'
  refForm.icon= undefined
  refForm.perms= undefined
  showFlag.value = false
}
const openUpdate = (node) => {
  Object.assign(refForm,node)

  showFlag.value = true
}
const open = (node) => {
  if (node) {
    const {menuId} = node
    refForm.parentId = menuId
    refForm.perms = undefined
  }
  showFlag.value = true
}
const linkChange = (label) => {
  if (label === '0') {
    refForm.isIframe = '1'
  }
}
const iframeChange = (label) => {
  if (label === '0') {
    refForm.isLink = '1'
  }
}

defineExpose({
  open,
  openUpdate
})

const subimt = async () => {
  await proxy.$refs.formView.validate((valid, fields) => {
    if (valid) {
      if (!refForm.menuId) {
        addMenu(refForm).then(res => {
          ElMessage.success(res.msg)
          cancel()
          emits('ok')
        })
      } else {
        editMenu(refForm).then(res => {
          ElMessage.success(res.msg)
          cancel()
          emits('ok')
        })
      }
    }
  })
}
let stateOptions = ref([])
let menuTypeOptions = ref([])
let commonIsNotOptions = ref([])

// 获取字典数据
const queryOptions = () => {
  proxy.$dictOptions('sys_common_status').then(res => {
    stateOptions.value = res.data
  })
  proxy.$dictOptions('sys_menu_type').then(res => {
    menuTypeOptions.value = res.data
  })
  proxy.$dictOptions('common_is_not').then(res => {
    commonIsNotOptions.value = res.data
  })
}

const menuTypeSelect = (dictValue) => {
  refForm.menuType = dictValue
  let title = refForm.title
  let parentId = refForm.parentId
  let perms = refForm.perms
  if (refForm.menuType === 'C') nameLabel.value = '菜单名称'

  else if (refForm.menuType === 'F') nameLabel.value = '按钮功能'
  formView.value.resetFields()
  refForm.title = title
  refForm.parentId = parentId
  refForm.perms = perms
  formView.value.clearValidate()
}

onBeforeMount(() => {
  queryOptions()
})

// 获取当前点击的 icon 图标
const onGetIcon = (icon) => {
  refForm.icon = icon
};
// 清空当前点击的 icon 图标
const onClearIcon = (icon) => {
};
</script>

<style scoped>

</style>
